from datetime import datetime

import yaml


def add(key, value):
    # 将结果写入指定文件
    with open("src/sr/pool.txt", 'a', encoding='utf-8') as file:
        file.write(key + ": " + value + "\n")  # 添加换行符，使文件内容更易读


def pool():
    # 读取YAML文件，指定编码为utf-8
    with open("src/sr/pool.yaml", 'r', encoding='utf-8') as stream:
        data = yaml.safe_load(stream)
    local_time = datetime.now()
    if local_time > datetime.strptime(data['mid_time'], "%Y-%m-%d %H:%M"):
        time = datetime.strptime(data['mid_time'], "%Y-%m-%d %H:%M") - local_time
    else:
        time = datetime.strptime(data['mid_time'], "%Y-%m-%d %H:%M") - local_time

    # 提取天数、小时数和分钟数
    days = time.days
    hours, remainder = divmod(time.seconds, 3600)
    minutes, _ = divmod(remainder, 60)
    # 格式化时间差
    formatted_time = f"{days}天{hours}小时{minutes}分钟"
    # 将结果写入指定文件
    with open("src/sr/pool.txt", 'w', encoding='utf-8') as file:
        file.write("持续时间： " + formatted_time + "\n")
    add("五星角色", str(data['five_star_char']).replace('&', '、'))
    add("五星武器", str(data['five_star_weapon']).replace('&', '、'))
    add("四星角色", str(data['four_star_char']).replace('&', '、'))
    add("四星武器", str(data['four_star_weapon']).replace('&', '、'))


def update(file, key, value):
    # 读取yaml文件
    with open(file, 'r', encoding='utf-8') as f:
        data = yaml.safe_load(f)
    if key in '五星角色':
        data['five_star_char'] = value
    elif key in '四星角色':
        data['four_star_char'] = value
    elif key in '五星武器':
        data['five_star_weapon'] = value
    elif key in '四星武器':
        data['four_star_weapon'] = value
    with open(file, 'w', encoding='utf-8') as f:
        yaml.dump(data, f, allow_unicode=True, sort_keys=False)
    with open(file, 'r', encoding='utf-8') as f:
        data = yaml.safe_load(f)
    if key in '五星角色':
        return "修改的内容为：" + key + ": " + data['five_star_char']
    elif key in '四星角色':
        return "修改的内容为：" + key + ": " + data['four_star_char']
    elif key in '五星武器':
        return "修改的内容为：" + key + ": " + data['five_star_weapon']
    elif key in '四星武器':
        return "修改的内容为：" + key + ": " + data['four_star_weapon'].replace('&', ' 、 ')
